package com.fs.user.web;

import com.fs.entity.Login;
import com.fs.service.LoginService;
import com.fs.service.impl.LoginServiceImpl;
import com.fs.util.VerifycodeUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //访问控制
        

        //2.获取表单提交的数据
        String user = request.getParameter("user");
        String password = request.getParameter("password");
        String verifycode = request.getParameter("verifycode");

        //3.调用service,
        LoginService loginService = new LoginServiceImpl();
        try {
            Login login  = loginService.login(user,password,verifycode, VerifycodeUtil.getCode(request));
            //把登录信息保存 域对象  session域
            request.getSession().setAttribute("login",login);


            //实现记住我功能
            String remember = request.getParameter("remember");
            if(remember!= null && !remember.isEmpty()){ //用户勾选了记住我
                //把用户名,密码已cookie形式保存到客户端浏览器
                Cookie userNameCookie = new Cookie("username",login.getUsername());
                Cookie pwdCookie = new Cookie("pwd",login.getPassword());

                userNameCookie.setMaxAge(7*24*60*60);
                pwdCookie.setMaxAge(7*24*60*60);

                userNameCookie.setPath("/");
                pwdCookie.setPath("/");

                //保存到客户端浏览器
                response.addCookie(userNameCookie);
                response.addCookie(pwdCookie);
            }

            //4.响应 跳转到index.jsp  重定向
            response.sendRedirect("/index.jsp");

        } catch (Exception e) {
            //往request存放错误数据
            request.setAttribute("errorMsg",e.getMessage());

            //跳转到error.jsp资源  请求转发
            request.getRequestDispatcher("/error.jsp").forward(request,response);
        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
